<template>
	<MainLayout>
		<view class="page">
			<!-- 头像 -->
			<view class="avatar-box" @click="chooseAvatar">
				<image :src="fullAvatar" class="avatar" />
				<view class="avatar-tips">点击更换头像</view>
			</view>

			<!-- 用户信息表单 -->
			<u-form :model="user" ref="form">
				<u-form-item label="昵称">
					<u-input v-model="user.nickname" placeholder="请输入昵称" />
				</u-form-item>

				<u-form-item label="手机号">
					<u-input v-model="user.mobile"  placeholder="请输入手机号" />
				</u-form-item>

				<u-form-item label="性别">
					<u-radio-group v-model="user.sex">
						<u-radio :name="0" label="保密"></u-radio>
						<u-radio :name="1" label="男"></u-radio>
						<u-radio :name="2" label="女"></u-radio>
					</u-radio-group>
				</u-form-item>
			</u-form>

			<!-- 保存按钮 -->
			<u-button type="primary" @click="saveInfo" class="save-btn">保存修改</u-button>
		</view>
	</MainLayout>
</template>

<script>
	import MainLayout from '@/layouts/MainLayout.vue'
	import api from '@/api'
	import {
		baseURL
	} from '@/utils/config.js'

	export default {
		components: {
			MainLayout
		},
		data() {
			return {
				user: {
					id: null,
					avatar: '',
					nickname: '',
					mobile: '',
					sex: 0
				},
				defaultAvatar:'/images/avatar/default.png',
			}
		},
		onShow() {
			this.loadUserInfo()
		},
		computed: {
			fullAvatar() {
				if (this.user.avatar) {
					// 如果 avatar 已经是完整地址（http 开头），直接返回
					if (this.user.avatar.startsWith('http')) {
						return this.user.avatar
					}
					// 否则拼接 baseURL
					return baseURL + this.user.avatar
				}
				// 默认头像
				return baseURL + this.defaultAvatar
			}
		},
		methods: {
			// 获取用户信息
			async loadUserInfo() {
				try {
					const res = await api.user.getUserInfo()
					if (res.code === 200 && res.data && res.data.userInfo) {
						const info = res.data.userInfo
						this.user = {
							id: info.id,
							avatar: info.avatar,
							nickname: info.nickname,
							mobile: info.mobile,
							sex: Number(info.sex) // 修复选不中问题
						}
					} else {
						uni.showToast({
							title: res.msg || '获取失败',
							icon: 'none'
						})
					}
				} catch (err) {
					console.error(err)
					uni.showToast({
						title: '获取失败',
						icon: 'none'
					})
				}
			},

			// 选择头像并上传
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]

						uni.showLoading({
							title: '上传中...'
						})

						uni.uploadFile({
							url: `${baseURL}/uploadcenter/v1/upload/file`,
							filePath: tempFilePath,
							name: 'file', // 后端接收字段名
							header: {
								Authorization: `Bearer ${uni.getStorageSync('token')}`
							},
							formData: {
								bizId: 'avatar',
								fileType: 'image'
							},
							success: (uploadRes) => {
								const data = JSON.parse(uploadRes.data)
								if (data.code === 200 && data.data) {
									this.user.avatar = data.data.url || tempFilePath
									this.saveInfo()							
									uni.showToast({
										title: '头像上传成功',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: data.msg || '上传失败',
										icon: 'none'
									})
								}
							},
							fail: (err) => {
								console.error(err)
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								})
							},
							complete: () => uni.hideLoading()
						})
					}
				})
			},

			// 保存用户信息
			async saveInfo() {
				try {
					const payload = {
						id: this.user.id,
						avatar: this.user.avatar,
						nickname: this.user.nickname,
						mobile: this.user.mobile,
						sex: this.user.sex
					}
					// console.log(payload,222222)
					// return
					const res = await api.user.updateUserInfo(payload)
					if (res.code === 200) {
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/mine/index'
							})
						}, 1500);
						
					} else {
						uni.showToast({
							title: res.msg || '修改失败',
							icon: 'none'
						})
					}
				} catch (err) {
					console.error(err)
					uni.showToast({
						title: '修改失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.page {
		padding: 20rpx;
		background-color: #fff;
	}

	.avatar-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.avatar-tips {
		font-size: 24rpx;
		color: #888;
	}

	.save-btn {
		margin-top: 40rpx;
	}
</style>